package com.sailing.xjpb.orm.intercepter;

import com.sailing.xjpb.common.sercurity.SailingUserContext;
import com.sailing.xjpb.orm.repository.SailingRepository;
import com.sailing.xjpb.orm.repository.SailingTenantRepository;
import lombok.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * 数据库持久层拦截器，代理实现了CrudRepository的所有repository
 *
 * @author YaoWei
 * createDate 2020年10月29日 下午1:37:10
 */
public class CrudRepositoryBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        if (bean instanceof SailingUserContext) {
            CrudRepositoryHandler.setUserContext((SailingUserContext) bean);
            TenantStatementInterceptor.setUserContext((SailingUserContext) bean);
            SailingTenantRepository.setUserContext((SailingUserContext) bean);
        }
        if (bean instanceof SailingTenantTableInitialization) {
            TenantStatementInterceptor.setSailingDataBaseInfoHandler((SailingTenantTableInitialization) bean);
        }
        // add by YaoWei since 2023-03-14
        if (bean instanceof CrudRepositoryOperatorHandler) {
            CrudRepositoryHandler.addOperatorHandler((CrudRepositoryOperatorHandler) bean);
        }
        // add by YaoWei since 2024-11-26
        if (bean instanceof SailingRepository) {
            CrudRepositoryHandler.setSailingRepository((SailingRepository) bean);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        return new CrudRepositoryHandler().proxyInstance(bean);
    }

}
